import logging

from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
# Create your views here.
from areas import constants
from areas.models import Areas
from meiduo_mall.utils.response_code import RETCODE

logger = logging.getLogger('django')

class AreasView(View):
    """省市区数据"""

    def get(self,request):
        """提供省市区数据"""
        area_id = request.GET.get('area_id')

        if not area_id:
            #提供省份数据
            # 检查缓存
            province_list = cache.get('province_list')
            if not province_list:
                try:
                    province_model_list = Areas.objects.filter(parent__isnull=True)
                    province_list = []
                    for province in province_model_list:
                        province_list.append({'id':province.id,'name':province.name})
                    # 缓存数据
                    cache.set('province_list',province_list,constants.CHCHE_EXPIRES)
                except Exception as e:
                    logger.error(e)
                    return JsonResponse({'code':RETCODE.DBERR,'errmsg':'省份数据错误'})
            return JsonResponse({'code':RETCODE.OK,'errmsg':'OK','province_list':province_list})
        else:
            #　提供市区或县数据
            # 检查缓存
            sub_data = cache.get('sub_area_'+area_id)
            if not sub_data:
                try:
                    sub_data = {}
                    province = Areas.objects.get(id=area_id)
                    sub_modles_list = province.subs.all()
                    sub_list = []
                    for sub in sub_modles_list:
                        sub_list.append({'id':sub.id,'name':sub.name})
                    sub_data = {'id': province.id, 'name':province.name,'subs':sub_list}
                    cache.set('sub_area_'+area_id,sub_data,constants.CHCHE_EXPIRES)
                except Exception as e:
                    logger.error(e)
                    return JsonResponse({'code':RETCODE.DBERR,'errmsg':'省份数据错误'})
            return JsonResponse({'code':RETCODE.OK,'errmsg':'OK','sub_data':sub_data})

